<?php
class Warehouse_Service_OnepieceProccess
{
	public function __construct(){			
		
	}
	
	/**
	 * 处理订单状态更新、库存更新
	 *
	 */
	public static function onepieceUpdate($productId,$orderCode,$wpbId)
	{			
		$productService = new Product_Service_Product();
		$adapter = $productService->getAdapter();
		$adapter->beginTransaction();		
		$data = array ('ask'=>0);
//		$orderInfo = Order_Service_Order ::getByOrdersCode($orderCode);		//订单信息
//		print_r($orderInfo);exit();
		
		try{
			$session = new Zend_Session_Namespace('userAuth');
			$user_id=$session->userID;					//操作人
			$orderInfo = Order_Service_Order ::getByOrdersCode($orderCode);		//订单信息
			$warehouseId = $orderInfo['warehouse_id'];							//仓库ID
			
			// warehouse_products_batch 批次表 hold 数量更新
			$wpbModel = new Warehouse_Model_ProductsBatch();
			$wpbInfo = $wpbModel->getByfield('wpb_id',$wpbId);			
			
			$wpbRowset = array();
			$wpbRowset['wpb_quantity_hold'] = $wpbInfo['wpb_quantity_hold'] - 1;
			if($wpbRowset['wpb_quantity_hold'] < 0 ){
				throw new Exception("订单：".$orderCode." 批次 ".$wpbId." 异常，数量<=0");
			}
			if($wpbRowset['wpb_quantity_hold'] == 0 && $wpbInfo['wpb_quantity'] == 0){
				$wpbRowset['wpb_status'] = 0;		//当前批次 库存与hold数量 都为 0时，状态更新为 0 
			}
			$affect = $wpbModel->update($wpbRowset,$wpbId);
			
			
			// warehouse_products 货架库存表 hold 数量更新
			$wpModelObj = new Warehouse_Model_Products();
			$cond = array();
			$cond['ws_code'] = $wpbInfo['ws_code'];
			$cond['warehouse_id'] = $warehouseId;
			$wpInfo = $wpModelObj->getByCondition($cond);		//返回一行数据
			
			$wpRowset = array();
			$wpRowset['wp_quantity_hold'] = $wpInfo['wp_quantity_hold'] - 1;
			if($wpRowset['wp_quantity_hold'] < 0 ){
				throw new Exception("订单：".$orderCode." 货架 ".$wpInfo['ws_code']." 库存异常，数量<=0");
			}
			$affect = $wpModelObj->update($wpRowset,$wpInfo['wp_id']);
						
			//货架使用日志
			$WarehouseProductsLog = array(
								'wpl_refId' => $orderCode,
								'user_id' => $user_id,
								'warehouse_id' => $warehouseId,
								'ws_code' => $wpInfo['ws_code'],
								'wpl_proc_type' => 4, //状态修改
								'wpl_note' => '下架更改货架库存，冻结库存由'.$wpInfo['wp_quantity_hold'].'变为'.$wpRowset['wp_quantity_hold']."。",
						);
			if (!Warehouse_Service_Products::CreateWarehouseProductsLog($WarehouseProductsLog)) {
					throw new Exception("订单：".$orderCode." 货架 ".$wpInfo['ws_code']." 写入使用日志失败失败");
			}
			
			// 更新订单状态
			$orderObj = new Order_Model_Order();
			$orderRowset = array();
			$orderRowset['process_status'] = 3;		//状态首先更新为 3:已下架	
// 			$orderRowset['package_user_id'] = $user_id;		//打包人
			$affect = $orderObj->update($orderRowset,$orderInfo['order_id']);	//最后更新时间在 update 方法已定义
			
			// 写订单状态日志，一共写两次
			$old_orders_status = $orderInfo['orders_status'];
			$old_process_status = $orderInfo['process_status'];
			$new_orders_status = $orderInfo['orders_status'];
			$new_process_status = 3 ;	//状态首先更新为 3:已下架 
			Order_Service_OrderProccess::createOrderLogNew($orderCode,$old_orders_status,$old_process_status,$new_orders_status,$new_process_status,$remark="",$frontShow=0);			
			
			$old_process_status = 3;
			$orderRowset['process_status'] = 4;
			$new_process_status = 4 ;	//状态然后更新为 4:待发货
			$affect = $orderObj->update($orderRowset,$orderInfo['order_id']);
			Order_Service_OrderProccess::createOrderLogNew($orderCode,$old_orders_status,$old_process_status,$new_orders_status,$new_process_status,$remark="",$frontShow=0);
			
			//获取物流单号
			$orderShipInfo = Order_Service_OrderShip::getLastRowByOrdersCode ($orderCode);
			$data['tracking_number'] = $orderShipInfo['tracking_number'];	

			$opm = new Order_Model_OrderPickupMap();			
			$opmRow = $opm->getByOrdersCode($orderCode);
			$opm->update(array('pack_user_id'=>$user_id,'opm_udate_date'=>date('Y-m-d H:i:s')), $opmRow['opm_id']);
			Order_Service_OrderPickup::updateByField(array('last_pack_orders_code'=>$orderCode), 'op_code', $opmRow['op_code']);
			$adapter->commit();
		}catch(Exception $e){
			$adapter->rollback();			
			return array('ask'=>0,'msg'=>array($e->getMessage()));		
		}
		
		$data['ask'] = 1;
		$data['orders_code'] = $orderCode;
		$data['msg'] = array($orderCode.' 操作成功。');
		return $data;	
	}
	
	
	/**
	 * 下架单扫描确认
	 *
	 */
	public static function scanConfirm($opCode)
	{
		$productService = new Product_Service_Product();
		$adapter = $productService->getAdapter();
		$adapter->beginTransaction();
		$data = array ('ask'=>0,'newpickup'=>array());

		try{			
    		$pickupRows = Order_Service_OrderPickupMap::getByfield('op_code',$opCode);
    		if(empty($pickupRows )){
    			throw new Exception('请确认下架单是否正确。');    			
    		}
    		$session = new Zend_Session_Namespace('userAuth');
			$user_id=$session->userID;     //操作人
			
    		$total = count($pickupRows);    	
    		$scanQuantity = 0;				// 已扫描数量
    		$scanOrderArr = $noScanOrderArr = array();		// 保存 已扫描和未扫描 的订单
    		$pickupUserIds = $pickupUserArr = array();
    		
    		if($total > 0){
    			foreach ($pickupRows as $key => $pickupRow){
					$orderInfo = Order_Service_Order::getByOrdersCode($pickupRow['orders_code']);
					if($orderInfo['process_status'] == 4){
						$scanQuantity++;
						$scanOrderArr[] = $pickupRow['orders_code'];
					}else {
						$noScanOrderArr[] = $pickupRow['orders_code'];
					}
				}
			
				// order_pickup 表，更新下架单信息
				$rowSet = array();
				$rowSet['op_order_cnt'] = $scanQuantity;	
				$rowSet['op_product_cnt'] = $scanQuantity;	
				$rowSet['op_status'] = 1;
				$rowSet['op_note'] = '';
				$rowSet['op_last_update'] = date('Y-m-d H:i:s');			
				$affect = Order_Service_OrderPickup::updateByField($rowSet,'op_code',$opCode);	//更新原来下架单的状态
			
				if(!empty($noScanOrderArr)){					
					$newOpcode = self::generateCode();		//新的下架单号
					$op_order_cnt = count($noScanOrderArr);		//一票一件
					$pickRow = array(
							  	"op_code" => $newOpcode,
								"op_creater_id" => $user_id,
								"op_order_cnt" => $op_order_cnt,
								"op_product_cnt" => $op_order_cnt,
								"op_status" => 0,	//配货单状态 草稿
								"op_create_date" => date("Y-m-d H:i:s") );
					//写 order_pickup 表
					$op_id = Order_Service_OrderPickup::add($pickRow);		
		
					foreach ($noScanOrderArr as $noScanOrder){
						$cond = array();
						$cond['op_code'] = $opCode;
						$cond['orders_code'] = $noScanOrder;				
						$rowSet = array();
						$rowSet['op_code'] = $newOpcode;	
						$rowSet['opm_create_date'] = date("Y-m-d H:i:s");
						
						$affect = Order_Service_OrderPickupMap::updateByCond($rowSet,$cond);
						
						// 获取 订单配货人 
						$orderInfo = Order_Service_Order ::getByOrdersCode($noScanOrder);		//订单信息
						$pickupUserIds[] = $orderInfo['pickup_user_id'];
						
						$cond = array();
						$cond['op_code'] = $newOpcode;
						$cond['orders_code'] = $noScanOrder;
						$pickupRow = Order_Service_OrderPickupMap::getRowByCond($cond);
						$productRow = Product_Service_Product::getProductInfo($pickupRow['product_id']);
						
						$orderInfo['ws_code'] = $pickupRow['ws_code'];
						$orderInfo['product_id'] = $pickupRow['product_id'];		//产品ID
						$orderInfo['product_sku'] = $productRow['product_sku'];
						$orderInfo['product_title'] = $productRow['product_title'];
						$orderInfo['category'] = $productRow['category'];
						
						$data['order'][] = $orderInfo;
												
					}
					$pickupUserIds = array_unique($pickupUserIds);
					foreach ($pickupUserIds as $pickupUserId){
						$userInfo = User_Service_User::getByUserId($pickupUserId);
						$pickupUserArr[] = $userInfo['name'];						//	配货人，下架人
					}
					$pickupUser = implode(',',$pickupUserArr);
					$operator = User_Service_User::getByUserId($user_id); 
					
					$data['pickupUser'] = $pickupUser;
					$data['operator'] = $operator['name'];
					$data['op_code'] = $newOpcode;
					$data['date'] = date("Y-m-d H:i:s");
					$data['msg'] = array('部分产品未配货，重新打印下架单');
				}
				
				$data['ask'] = 1;
    		}
    	
			$adapter->commit();
		}catch(Exception $e){
			$adapter->rollback();			
			return array('ask'=>0,'msg'=>array($e->getMessage()));		
		}
		
		return $data;
	}	
	
	//生成下架单号
	public static function generateCode(){
		$sequence = "001";
		$offShelfModel = new Product_Model_OrderPickup();
		$offShelfs = $offShelfModel->getMaxByCurrentDate()->toArray();
		if(!empty($offShelfs)){
			$currentCode = current($offShelfs);
			$currentCode = substr($currentCode['op_code'],-3);
			$sequence = str_pad($currentCode + 1,3,"0",STR_PAD_LEFT);
		}
		$code = "U".date("ymd").$sequence;
		return $code;
	}
		
}
